<template>
  <bd-popup
    class="custom"
    popupId="lotteryV3ChestShare"
    :weights="2.9"
    v-model:show="props.show"
    :style="{
      'background-color': 'transparent',
      overflow: 'initial',
    }"
    zIndex="999996"
    teleport="body"
    :overlay-style="{ background: 'rgba(0, 0, 0, 0.5)' }"
    :close-on-click-overlay="false"
  >
    <!-- 背景光环 -->
    <img class="gh" src="/image/inviteFriends/ferr-gh-icon.svg" />
    <!-- 蝴蝶结 -->
    <img class="hdj" src="/image/inviteFriends/free-hdj-icon.svg" />
    <!-- 容器 -->
    <div class="box">
      <div class="box-box">
        <div class="box-box-box">
          <!-- 标题 -->
          <div class="box-title">
            <!-- 容器背景 -->
            <img class="box-title-bg" src="/image/titlebg-icon.svg" />
            <!-- 标题 -->
            <div class="box-title-value">
              {{ $t("lotteryMoney.fxghy") }}
            </div>
          </div>
          <!-- 描述 -->
          <div class="box-desc">
            {{ $t("lotteryMoney.ljhdmfxz").replace("xxx", num + "") }}
          </div>
          <!-- 卡片 -->
          <div class="box-card items-center">
            <div class="box-card-left">
              <div class="box-card-left-box items-center">
                <div class="box-card-left-title">
                  {{ $t("lotteryMoney.freeCard") }}
                </div>
                <!-- <div class="box-card-left-desc">
                  {{ $t("lotteryMoney.jjclose").replace("xxx", "") }}
                  <span style="color: #002853"
                    >{{ hours }}:{{ minutes }}:{{ seconds }}</span
                  >
                </div> -->
              </div>
            </div>
            <div class="box-card-right items-center">
              <img
                class="box-card-right-bg"
                src="/image/lottery-v3/chest-cardbg-icon.svg"
              />
              <div class="box-card-right-title">*{{ num }}</div>
            </div>
          </div>

          <!-- 底部按钮 -->
          <div class="box-footer">
            <div class="box-footer-top items-center">
              <div class="box-footer-top-left">{{ $t("lotteryMoney.lj") }}</div>
              <!-- 地址 -->
              <div class="box-footer-top-center">
                {{ shareUrl }}
              </div>
              <!-- 复制按钮 -->
              <img
                class="box-footer-top-copy"
                src="/image/inviteFriends/footer-copy.svg"
                @click.stop="saveCopy"
              />
            </div>

            <div class="box-footer-btn" @click.stop="confirm">
              {{ $t("lotteryMoney.fxghy") }}
            </div>
          </div>
        </div>
      </div>
      <!-- 底部按钮-背景 -->
      <img
        class="box-footer-bg"
        src="/image/lottery-v3/chest-share-footerbg.svg.svg"
      />
    </div>
    <!-- 关闭 -->
    <!-- <img
      class="close"
      src="/image/close-fff-icon.svg"
      @click.stop="closePopup"
    /> -->
  </bd-popup>
</template>
<script setup lang="ts" name="chestPopup">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { claimNewUserBonus } from "@/api/lottery";
import { useEventBus, useClipboard, useDateFormat } from "@vueuse/core";
import { useGlobalStore } from "~~/store/global";
import { useLotteryV3Store } from "~~/store/modules/lottery-v3";

const props = withDefaults(
  defineProps<{
    show: boolean;
    num: number;
  }>(),
  {
    show: false,
    num: 1,
  }
);

const emit = defineEmits(["update:show", "confirm", "countdownDone"]);
const { t } = useI18n();

const globalStore = useGlobalStore();
const lotteryStore = useLotteryV3Store();

const file = getOssFileUrl({
  avatarDefault: "/image/avatar-default.png",
  sharePage: "/invite-friends/v3/invite",
});

// 点击确认
const confirm = () => {
  // 1. 领取
  showLoadingToast({
    message: `${t("common.requestIng")}...`,
    forbidClick: true,
    duration: 15000,
  });

  claimNewUserBonus({
    sourceType: 2,
    prizeType: 6,
  }).then((res) => {
    if (res) {
      // 提示
      // showToast({
      //   message: `${t("pledge.lqcg")},${t("lotteryMoney.mfxz")} *${
      //     res.freeDrawCount || 1
      //   }`,
      //   "z-index": 9999999,
      // });

      // 关闭弹窗 并且 传递: 用户全部可用免费次数
      emit("confirm", res.freeDrawCount);
    } else {
      closePopup();
    }
  });
};

/****************** 复制 ******************/
// 分享地址
const shareUrl = computed(() => {
  return (
    file.sharePage +
    "?hiddenBar=1" +
    `&language=${globalStore.$state.language}` +
    `&packageId=${globalStore.$state.packageId}` +
    `&sourceType=12` +
    `&code=${lotteryStore.$state.inviteLotteryCode}`
  );
});

const saveCopy = () => {
  if (!file.sharePage) return;
  const { copy, isSupported } = useClipboard({
    source: "",
  });
  if (!isSupported.value) {
    showToast({
      message: t("mvp.other.bzcjtb"),
      "z-index": 9999999,
    });
  } else {
    copy(shareUrl.value);
    showToast({
      message: t("mvp.other.fzcg"),
      "z-index": 9999999,
    });
  }
};

/****************** 分享 ******************/
let shareLoading = false;
const shareApp = () => {
  if (shareLoading) return;
  try {
    shareLoading = true;
    console.log("分享地址:", shareUrl.value);
    bridge.onShare(t("lotteryMoney.hyzldmfcj"), shareUrl.value);
  } catch (error) {
    console.log(error);
  } finally {
    // 延时 1s，防止用户连续点击
    setTimeout(() => {
      shareLoading = false;
    }, 1000);
  }
};

// 关闭弹窗
const closePopup = () => {
  emit("update:show", false);
};

/****************** 倒计时 ******************/
// 未开始倒计时
let unsubscribeFns: any = {}; // 执行的函数数组
let hours = ref("--");
let minutes = ref("--");
let seconds = ref("--");
const isCountdownDone = ref(false); // 倒计时,是否结束
// 设置倒计时结束时间
let endTime = Number(lotteryStore.$state.chestWlSource.endTime || 0); // 默认: recordStatus == 2 的结束时间

function updateLotteryCountdown() {
  if (!lotteryStore.$state.chestWlSource.recordStatus) return;
  // 倒计时结束通知一次
  let isRefrrsh = false;
  // 计算函数
  const updateCountdown = (now: any) => {
    if (Number(endTime) <= 0) return;
    const distance = endTime - Number(now);
    // 1. 倒计时结束时的处理
    if (distance < 0 && !isRefrrsh) {
      isRefrrsh = true;
      setTimeout(() => {
        isCountdownDone.value = true;
        // emit("countdownDone");
        console.log(
          "倒计时结束时间:",
          useDateFormat(endTime, "YYYY-MM-DD HH:mm:ss").value
        );

        console.log(endTime, "-", now, "倒计时结束:", distance);
        closePopup();
      }, 500);
      return;
    }
    // 2. 计算剩余的小时、分钟和秒
    if (distance >= 0) {
      hours.value = `${Math.floor(
        (distance % (1000 * 60 * 60 * 24 * 7)) / (1000 * 60 * 60)
      )}`;
      if (Number(hours.value) < 10) hours.value = `0${hours.value}`;
      minutes.value = `${Math.floor(
        (distance % (1000 * 60 * 60)) / (1000 * 60)
      )}`;
      if (Number(minutes.value) < 10) minutes.value = `0${minutes.value}`;
      seconds.value = `${Math.floor((distance % (1000 * 60)) / 1000)}`;
      if (Number(seconds.value) < 10) seconds.value = `0${seconds.value}`;
    }
  };
  // 3. 先执行一次,不然要等一秒才能计算
  const ckbzTime = new Date("2024/01/01").getTime();
  if (Number(globalStore.$state.serverTime) > ckbzTime) {
    updateCountdown(globalStore.$state.serverTime);
  }

  // 4. 定时执行
  unsubscribeFns["updateLotteryCountdown"] = (val: number) => {
    updateCountdown(val);
  };
}

// 定时器-通知
// let unsubscribe: any = null; // 定时器通知对象
// const lotteryInterval = useEventBus("lottery-v3-interval-emit");
onMounted(() => {
  // // 1. 统一的定时器,通知,组件加载的时候只初始化一次
  // if (!unsubscribe) {
  //   unsubscribe = lotteryInterval.on((val: any) => {
  //     if (unsubscribeFns && Object.keys(unsubscribeFns).length > 0) {
  //       Object.keys(unsubscribeFns).forEach((key: any) => {
  //         const fn = unsubscribeFns[key];
  //         if (fn && typeof fn === "function") {
  //           fn(val);
  //         }
  //       });
  //     }
  //   });
  // }
  // // 2.
  // updateLotteryCountdown();
});

onBeforeUnmount(() => {
  // if (unsubscribe) unsubscribe(); // 注销通知
  // recordStatus_watch && recordStatus_watch();
});
</script>
<style lang="scss" scoped>
.gh {
  position: absolute;
  top: -92 * 2px;
  width: 100vw;
}
.hdj {
  position: absolute;
  z-index: 10;
  left: 50%;
  transform: translateX(-50%);
  top: -48 * 2px;
}
.box {
  position: relative;
  z-index: 9;
  margin: 0 40 * 2px;
  background: linear-gradient(90deg, #007bff 0.07%, #00b2ff 99.93%);
  border-radius: 12 * 2px;
  overflow: hidden;
  padding: 4 * 2px 4 * 2px 4 * 2px 4 * 2px;
  &-box {
    background: linear-gradient(0deg, #fff 59.68%, #fff6eb 100%);
    border-radius: 12 * 2px;
    overflow: hidden;
    padding: 4 * 2px 4 * 2px 0 4 * 2px;
    &-box {
      background: linear-gradient(0deg, #fff 59.68%, #fff6eb 100%);
      border-radius: 12 * 2px;
      overflow: hidden;
      padding: 10 * 2px 7 * 2px 0 7 * 2px;
      border: 1px solid #ffefdb;
      position: relative;
    }
  }
  &-title {
    width: 100%;
    height: 30 * 2px;
    position: relative;
    margin-bottom: 10 * 2px;
    &-bg {
      position: absolute;
      top: 0;
      height: 30 * 2px;
    }
    &-value {
      position: relative;
      z-index: 9;
      height: 30 * 2px;
      line-height: 30 * 2px;
      width: 100%;
      text-align: center;
      font-size: 15 * 2px;
      color: #fff;
      font-weight: 590;
    }
  }

  &-desc {
    text-align: center;
    font-size: 12 * 2px;
    color: #141924;
    margin-bottom: 10 * 2px;

    &-name {
      font-size: 15 * 2px;
      color: #007bff;
      font-weight: 590;
    }
  }

  &-card {
    position: relative;
    justify-content: space-between;
    height: 70 * 2px;
    margin-bottom: 60 * 2px;
    &-left {
      width: calc(100% - 40 * 2px);
      height: 100%;
      border: 4 * 2px solid #00b2ff;
      border-right-width: 0;
      padding: 3 * 2px;
      border-radius: 8 * 2px;
      background: linear-gradient(90deg, #e3f5ff 0%, #c7e3ff 100%);

      &-box {
        width: calc(100% - 20 * 2px);
        height: 100%;
        border-radius: 6 * 2px;
        padding: 2 * 2px 6 * 2px;
        flex-direction: column;
        justify-content: space-around;
        border: 0.7px solid rgba(75, 164, 255, 0.1);
        align-items: flex-start;
      }
      &-title {
        color: #002853;
        font-size: 12 * 2px;
        font-weight: 590;
        margin-bottom: 4 * 2px;
      }
      &-desc {
        color: #999da7;
        font-size: 11 * 2px;
        font-weight: 400;
      }
    }
    &-right {
      position: absolute;
      top: 0;
      right: 0;
      width: 65 * 2px;
      height: 100%;
      justify-content: center;

      &-bg {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
      }
      &-title {
        position: relative;
        z-index: 9;
        color: #ffe771;
        font-size: 17 * 2px;
        font-weight: 700;
      }
    }
  }

  &-footer {
    position: relative;
    margin-top: -11 * 2px;
    justify-content: center;
    align-items: end;
    height: 90 * 2px;

    &-top {
      position: relative;
      z-index: 9;
      width: 100%;
      border-radius: 4 * 2px;
      background: #f0f3fa;
      margin-bottom: 10 * 2px;

      &-left {
        padding: 6 * 2px 0 * 2px;
        margin: 0 8 * 2px;
        color: #999da7;
        font-size: 14 * 2px;
        font-weight: 400;
      }
      &-center {
        @include multi-line-omit(1);
        flex: 1;
        // text-wrap: nowrap;
        // white-space: nowrap;
        color: #141924;
        font-size: 14 * 2px;
        font-weight: 600;
        margin-right: 8 * 2px;
      }
      &-copy {
        height: 100%;
      }
    }

    &-bg {
      position: absolute;
      bottom: 2 * 2px;
      z-index: 8;
      width: 100%;
      height: 135 * 2px;
      margin-left: -4 * 2px;
    }

    &-btn {
      position: relative;
      z-index: 9;
      border-radius: 100px;
      background: linear-gradient(270deg, #fb7f09 0.03%, #ffb901 99.97%);
      color: #fff;
      font-size: 15 * 2px;
      font-weight: 590;
      text-align: center;
      width: 100%;
      padding: 10 * 2px 12 * 2px;
      margin-bottom: 16 * 2px;
    }

    &-record {
      position: relative;
      z-index: 9;
      margin-bottom: 16 * 2px;
      width: 36 * 2px;
      height: 36 * 2px;
      margin-left: 10 * 2px;
    }
  }
}
.close {
  position: relative;
  z-index: 9;
  bottom: -30 * 2px;
  left: 50%;
  transform: translateX(-50%);
  width: 30 * 2px;
  height: 30 * 2px;
}
</style>
